package jvm;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @program RCS
 * @description: 加密签名
 * @author: zhanglu
 * @create: 2020-10-27 20:27:00
 */
@Slf4j
public class TokenSignatureUtils {

    private final static String ENCRYPT_KEY = "123456";

    /**
     * 加密
     *
     * @param params
     * @return
     */
    public static String encryptStr(String params) {
        SecretKeySpec keySpec = new SecretKeySpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8), SymmetricAlgorithm.AES.getValue());
        IvParameterSpec iv = new IvParameterSpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8));
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, keySpec, iv);
        String encryptBase64 = aes.encryptHex(params);
        return encryptBase64;
    }

    /**
     * 解密
     *
     * @param params
     * @return
     */
    public static String decryptStr(String params) {
        SecretKeySpec keySpec = new SecretKeySpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8), SymmetricAlgorithm.AES.getValue());
        IvParameterSpec iv = new IvParameterSpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8));
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, keySpec, iv);
        String encryptBase64 = aes.decryptStr(params);
        return encryptBase64;
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static byte[] encryptByte(byte[] data) {
        SecretKeySpec keySpec = new SecretKeySpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8), SymmetricAlgorithm.AES.getValue());
        IvParameterSpec iv = new IvParameterSpec(ENCRYPT_KEY.getBytes(StandardCharsets.UTF_8));
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, keySpec, iv);
        return aes.encrypt(data);
    }

}

